package com.petcommunity.servlet;

import com.petcommunity.dao.AdoptionDAO;
import com.petcommunity.model.Adoption;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.sql.Date;
@WebServlet("/adoptions")
public class AdoptionServlet extends HttpServlet {

    private AdoptionDAO adoptionDAO = new AdoptionDAO();

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Adoption> adoptions = adoptionDAO.getAllAdoptions();
        request.setAttribute("adoptions", adoptions);
        request.getRequestDispatcher("adoptions.jsp").forward(request, response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应的字符编码为 UTF-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        try {
    Adoption adoption = new Adoption();
    adoption.setPetId(Integer.parseInt(request.getParameter("petId")));
    adoption.setAdopterName(request.getParameter("adopterName"));
    adoption.setAdopterPhone(request.getParameter("adopterPhone"));
    java.util.Date utilDate = new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("adoptionDate"));
    adoption.setAdoptionDate(new java.sql.Date(utilDate.getTime()));
    adoptionDAO.addAdoption(adoption);
    response.sendRedirect("adoptions");
} catch (Exception e) {
    e.printStackTrace();
    response.sendRedirect("error.jsp");
}

    }
}
